<template>
  <view>

    <cu-custom isBackFunc @back="hanleBackPageFunc">
      <!-- #ifdef MP -->
      <block slot="left">
        <view class="text-xxl action right" @click="handleInviteMember">
          <button class="cu-btn sm radius" :class="selectId.length?'bg-green': 'bg-grey'">确定({{selectId.length || 0}}
            )</button>
        </view>
      </block>
      <!-- #endif -->
      <block slot="content">{{data.title}} <text class="text-xs text-gray">可邀请{{len}}人</text> </block>
      <!-- #ifndef MP -->
      <block slot="right">
        <view class="text-xxl action right" @click="handleInviteMember">
          <button class="cu-btn sm radius"
            :class="selectId.length?'bg-green': 'bg-grey'">确定({{selectId.length || 0}})</button>
        </view>
      </block>
      <!-- #endif -->
    </cu-custom>
    <view class="mainpageitem">
      <!-- #ifdef APP-PLUS -->
      <u-sticky :offset-top="CustomBar">
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <u-sticky :offset-top="StatusBar + 1">
          <!-- #endif -->
          <view class="cu-bar search bg-white shadow-xs">
            <view class="search-form round padding-right-xs">
              <text class="cuIcon-search"></text>
              <u-input clearable border="none" placeholder="输入关键字搜索" v-model="queryValue" @input="handleQuery">
              </u-input>
            </view>
          </view>
        </u-sticky>
        <custom-index-list :index-list="indexList" v-if="indexList.length>0" :customNavHeight="CustomBar + 50">
          <view class="user-list" v-for="(item, index) in itemArr" v-if="itemArr.length>0">
            <custom-index-item>
              <u-index-anchor :text="indexList[index]" bgColor="#f5f5f5"></u-index-anchor>
              <view class="user-item" v-for="(items,indexs) in item" @click="handleSelect(items)">
                <u-avatar shape="square" :src="getAvatar(items.id)"></u-avatar>
                <view class="user-nick">{{items.name}}</view>
                <view class="flex-check">
                  <checkbox class="green"
                    :disabled="(selectId.length >= len && !selectId.includes(items.id) && !isNew(items).add) || items.id == user.id || isNew(items).add"
                    :checked="selectId.includes(items.id) || items.id == user.id || isNew(items).add?true:false"
                    :class="{checked: selectId.includes(items.id) && items.id != user.id && !isNew(items).add, me: items.id == user.id || isNew(items).add}" />
                </view>
              </view>
            </custom-index-item>
          </view>
        </custom-index-list>
        <view class="text-empty" v-else>
          <text v-if="friends.inited">{{ text.text_empty }}</text>
          <text v-else class="cu-load load-cuIcon loading">好友加载中...</text>
        </view>
    </view>
  </view>
</template>

<script>
  import core from "@/core.js"
  import store from '@/store'
  import Pinyin from '@/utils/ChinesePY.js';
  import * as API_friend from '@/api/friend'
  import customIndexList from '@/components/util/custom-index-list/u-index-list/u-index-list'
  import customIndexItem from '@/components/util/custom-index-list/u-index-item/u-index-item'
  import {
    findFriends,
  } from '@/data/common'
  import siteinfo from '@/siteinfo'
  import {
    mapGetters
  } from 'vuex'
  export default {
    components: {
      customIndexList,
      customIndexItem
    },
    data() {
      return {
        len: siteinfo.rtcGroupMemberLimit -1,
        add: false,
        type: 'voices',
        gid: 0,
        queryValue: '',
        selectItem: [],
        inviteForm: {},
        memberData: {},
        selectId: [],
        friends: {
          inited: false,
          data: [],
          totals: 0
        },
        data: {
          title: "选择参会人"
        },
        text: core.langs,
      }
    },
    computed: {
      indexList() {
        const {
          data
        } = this.useLetter([...this.friends.data]);
        let indexList = [];
        data.forEach(item => {
          indexList.push(item.letter)
        })
        return indexList
      },
	  
      itemArr() {
        const {
          data
        } = this.useLetter([...this.friends.data]);
        let itemArr = [];
        data.forEach(item => {
          itemArr.push(item.data)
        })
        return itemArr
      },
      isNew(data) {
        return data => {
          // console.log(this.selectItem.find(el => el.id == data.id))
          return (this.selectItem.find(el => el.id == data.id) || {})
        }
      }
    },
    onLoad(options) {
      this.type = options.type
      if (options.group) {
        this.memberData = JSON.parse(options.group) 
        this.add = options.add
		// 总限制成员个数，减去自己，减去已经在通话中的人
		this.len = (this.siteinfo.rtcGroupMemberLimit- 1)
		console.log(this.memberData);
		this.memberData.forEach(el=>{
			if(el.id!=this.user.id){
				const obj = {}
				obj.uid = Number(el.id)
				obj.id = Number(el.id)
				obj.add = options.add
				obj.name = el.name
				this.selectItem.push(obj)
				this.selectId.push(Number(el.id))
			}
		})
		console.log('this.selectItem',this.selectItem);
		console.log('this.selectId',this.selectId)
      }
      this.initData();
    },
    methods: {
	  // 唤起
	  selectUser(group){
		this.add='add';
		this.memberData = group;
		this.len = (this.siteinfo.rtcGroupMemberLimit- 1);
		this.memberData.forEach(el=>{
			if(el.id!=this.user.id){
				const obj = {}
				obj.uid = Number(el.id)
				obj.id = Number(el.id)
				obj.add = 'add'
				obj.name = el.name
				this.selectItem.push(obj)
				this.selectId.push(Number(el.id))
			}
		})
		this.initData();
	  },
	  hanleBackPageFunc(){
	  		if(this.add)this.$emit('close')
	  		else core.back()
	  },
      async initData(name) {
        this.$set(this.friends, 'inited', false)
        const friends = await findFriends(name)
        this.$set(this.friends, 'data', friends)
        this.$set(this.friends, 'inited', true)
      },
      // 整理通讯录
      useLetter(arr) {
        arr = arr.filter(item => item.id != this.user.id)
        const friends = {
          data: []
        };
        const fd = arr.sort((a, b) => {
          return a.name.localeCompare(b.name);
        });
        const tt = fd.map(item => {
          return {
            letter: Pinyin.getWordsCode(item.name).toUpperCase(),
            data: [{
              id: item.id,
              name: item.name,
              alias: item.alias,
              motto: item.motto,
              telephone: item.telephone,
              organizationId: item.organizationId,
              organizationName: item.organizationName,
              departName: item.departName,
              title: item.title,
            }]
          };
        });
        tt.map(item => {
          const isT = friends.data.find(c => c.letter === item.letter);
          if (!isT) {
            friends.data.push(item);
          } else {
            isT.data.push(item.data[0]);
          }
        });
        friends.data = friends.data.sort((a, b) => a.letter.localeCompare(b.letter));
        return friends;
      },
      // 搜索功能
      handleQuery(e) {
        this.initData(this.queryValue)
      },
      handleSelect(item) {
        const index = this.selectId.indexOf(item.id)
		if ((this.selectId.length >= this.len && !this.selectId.includes(item.id) && !this.isNew(item).add) 
			|| item.id == this.user.id || this.isNew(item).add) {
          return
        }
        if (this.selectId.includes(item.id)) {
          this.selectItem.splice(index, 1)
          this.selectId.splice(index, 1)
        } else {
          this.selectItem.push(item)
          this.selectId.push(item.id)
        }
      },
      handleInviteMember() {
        if (this.selectId.length === 0) {
          core.toast('请先选择成员')
          return
        }
        store.commit('user/SET_ONLINE', true);
		console.log(this.add);
        if (this.add) {
			
		  let list = this.selectItem.filter(el=>{
			  return !el.add
		  })
		  // uni.$emit('inviteLivekit', list);
          this.add = false
		  this.$emit('inviteLivekit',list)
          // return core.back()
		  return;
        }
        let group = JSON.stringify(this.selectItem)
		this.naviTo('livekit/metting?type=quick&group=' + encodeURIComponent(group),{},2);
      }
    }
  }
</script>
<style lang="scss">
  .user-list {
    .u-index-anchor {
      border: none;
    }

    .user-item {
      display: flex;
      align-items: center;
      flex-direction: initial;
      height: 120rpx;
      padding-left: 20rpx;
      border-bottom: 2rpx solid #ebebeb;
      background: #fff;
      position: relative;

      .user-nick {
        flex: 1;
        padding-left: 20rpx;
      }

      .flex-check {
        flex-basis: 15%;

        checkbox[disabled] {
          &:not(.checked) {
            &::before {
              content: ''
            }
          }

          &.me {
            &::before {
              content: "\e645"
            }
          }
        }
      }
    }
  }

  .originClass {
    position: absolute;
    top: 10rpx;
    left: 80rpx;
    background: #fff;
    padding: 4rpx;
    border-radius: 50%;
  }

  .search-form {
    transition: all 0.3;
  }
  .mainpageitem{
	  background-color: #fff;
	  height: 95vh !important;
  }
</style>